//
//  NSObject+MDHOcExtension.m
//  JSTech
//
//  Created by 华&梅 on 2019/9/27.
//  Copyright © 2020 华&梅. All rights reserved.
//

#import "NSObject+MDHOcExtension.h"
#import "JSTech-Swift.h"
#import <objc/runtime.h>

@implementation NSObject (MDHOcExtension)

@end


@interface MDHFileConstant()
<
AMapLocationManagerDelegate
>

///默认定位
@property (nonatomic, strong, readwrite) CLLocation * _Nonnull location;
///定位功能
@property (nonatomic, strong, readwrite) AMapLocationManager * locationManager;
///定位的block 回调
@property (nonatomic, copy) blockAMapLocation locationMBlock;
///当前的longitude
@property (nonatomic, copy, readwrite) NSString * _Nonnull longitude;
///当前的latitude
@property (nonatomic, copy, readwrite) NSString * _Nonnull latitude;

@end

@implementation MDHFileConstant (MDHOcExtension)

///定位///当前的longitude///当前的latitude///当前的locationManager
@dynamic location, longitude, latitude;

///WebView的管理者
+ (MDHWKWebViewManager *_Nonnull)webVc {
    return [MDHWKWebViewManager share];
}

///set方法
- (void)setLocation:(CLLocation *)location {
    if (location == nil) {
        return;
    }
    objc_setAssociatedObject(self, @selector(location), location, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    NSString * keylongitude = [[self className] stringByAppendingString:@"location_longitude"];
    NSString * keylatitude = [[self className] stringByAppendingString:@"location_latitude"];
    [[NSUserDefaults standardUserDefaults] setDouble:location.coordinate.longitude forKey:keylongitude];
    [[NSUserDefaults standardUserDefaults] setDouble:location.coordinate.latitude forKey:keylatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
///默认的定位
- (CLLocation *)location {
    NSString * keylongitude = [[self className] stringByAppendingString:@"location_longitude"];
    NSString * keylatitude = [[self className] stringByAppendingString:@"location_latitude"];
    CGFloat longitude = [[NSUserDefaults standardUserDefaults] doubleForKey:keylongitude];
    CGFloat latitude = [[NSUserDefaults standardUserDefaults] doubleForKey:keylatitude];
    longitude = longitude == 0 ? 0:longitude;//120.38
    latitude = latitude == 0 ? 0:latitude;//36.07
    self.location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    return objc_getAssociatedObject(self, @selector(location));
}
///
- (NSString *)longitude {
    CGFloat longitude = self.location.coordinate.longitude;
    if (longitude == 0) {
        return @"";
    }
    return [NSString stringWithFormat:@"%lf",longitude];
}
///
- (NSString *)latitude {
    CGFloat latitude = self.location.coordinate.latitude;
    if (latitude == 0) {
        return @"";
    }
    return [NSString stringWithFormat:@"%lf",latitude];
}
//MARK: 高德定位 定位
///开始定位
- (void)locationStart:(blockAMapLocation)completionBlock {
    if (self.locationManager == nil) {
        self.locationMBlock = completionBlock;
        //初始化实例
        AMapLocationManager * lm = [[AMapLocationManager alloc] init];
        //设置delegate
        lm.delegate = self;
        //设置返回位置的坐标系类型 // 带逆地理信息的一次定位（返回坐标和地址信息）
        //_locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设置距离过滤参数
        lm.distanceFilter = kCLDistanceFilterNone;
        //设置预期精度参数
        //_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        [lm setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
        //设置应用位置类型
        //_locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //设置是否自动停止位置更新
        lm.pausesLocationUpdatesAutomatically = false;
        //设置是否允许后台定位
        //_locationManager.allowsBackgroundLocationUpdates = YES;
        //设置位置获取超时时间//   定位超时时间，最低2s，此处设置为2s
        lm.locationTimeout = 2;
        //设置获取地址信息超时时间//   逆地理请求超时时间，最低2s，此处设置为2s
        lm.reGeocodeTimeout = 2;
        [lm setLocatingWithReGeocode:true];
        self.locationManager = lm;
    }
    [self.locationManager startUpdatingLocation];
}
- (void)setLocationManager:(AMapLocationManager *)locationManager {
    objc_setAssociatedObject(self, @selector(locationManager), locationManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (AMapLocationManager *)locationManager {
    return objc_getAssociatedObject(self, @selector(locationManager));
}
- (void)setLocationMBlock:(blockAMapLocation)locationMBlock {
    objc_setAssociatedObject(self, @selector(locationMBlock), locationMBlock, OBJC_ASSOCIATION_COPY);
}
- (blockAMapLocation)locationMBlock {
    return objc_getAssociatedObject(self, @selector(locationMBlock));
}
/////定位结束
- (void)locationStop {
    if (self.locationManager) {
        [self.locationManager stopUpdatingLocation];
        self.locationManager.delegate = nil;
        self.locationManager = nil;
        self.locationMBlock = nil;
    }
//    //1.将两个经纬度点转成投影点
//    MAMapPoint point1 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(39.989612,116.480972));
//    MAMapPoint point2 = MAMapPointForCoordinate(CLLocationCoordinate2DMake(39.990347,116.480441));
//    //2.计算距离
//    CLLocationDistance distance = MAMetersBetweenMapPoints(point1,point2);
}
/**
 *  @brief 当plist配置NSLocationAlwaysUsageDescription或者NSLocationAlwaysAndWhenInUseUsageDescription，并且[CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined，会调用代理的此方法。
 此方法实现调用申请后台权限API即可：[locationManager requestAlwaysAuthorization](必须调用,不然无法正常获取定位权限)
 *  @param manager 定位 AMapLocationManager 类。
 *  @param locationManager  需要申请后台定位权限的locationManager。
 *  @since 2.6.2
 */
- (void)amapLocationManager:(AMapLocationManager *)manager doRequireLocationAuth:(CLLocationManager *)locationManager
{
    [locationManager requestAlwaysAuthorization];
}

/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error {
    if (self.locationMBlock) {
        self.locationMBlock(nil, nil, error);
    }
    [self locationStop];
}

/**
 *  @brief 连续定位回调函数.注意：如果实现了本方法，则定位信息不会通过amapLocationManager:didUpdateLocation:方法回调。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param location 定位结果。
 *  @param reGeocode 逆地理信息。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode{
    if (location) {
        self.location = location;
    }
    if (self.locationMBlock) {
        self.locationMBlock(location, reGeocode, nil);
    }
    [self locationStop];
}

/**
 *  @brief 定位权限状态改变时回调函数
 *  @param manager 定位 AMapLocationManager 类。
 *  @param status 定位权限状态。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
}

/**
 *  @brief 是否显示设备朝向校准
 *  @param manager 定位 AMapLocationManager 类。
 *  @return 是否显示设备朝向校准
 */
- (BOOL)amapLocationManagerShouldDisplayHeadingCalibration:(AMapLocationManager *)manager {
    return false;
}

/**
 *  @brief 设备方向改变时回调函数
 *  @param manager 定位 AMapLocationManager 类。
 *  @param newHeading 设备朝向。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
}


//MARK: -===== 配置 页面跳转
/// 这里是viewModel -> ViewController的映射
/// If You Use Push 、 Present 、 ResetRootViewController ,You Must Config This Dict
- (void)viewModelViewMappings {
    [[MDHRouter sharedInstance] viewModelViewMappings:@{
        /// Word
        @"JSTDocListViewController":@"JSTDocListViewModel",///doc的列表
        @"JSTDocListViewModel":@"JSTDocListViewController",///doc的列表
        @"JSTPIncomeTaxViewController":@"JSTPIncomeTaxViewModel",///个人所得税
        
        /// tabbar
        @"JSTTabbarViewController":@"JSTTabbarViewModel",///
    }];
}

@end
